package com.chenyuxin.ilp.service.user.Impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chenyuxin.ilp.exception.BaseException;
import com.chenyuxin.ilp.mapper.user.UserMapper;
import com.chenyuxin.ilp.model.constant.RedisConstant;
import com.chenyuxin.ilp.model.constant.UserSuccessConstant;
import com.chenyuxin.ilp.model.entity.user.User;
import com.chenyuxin.ilp.model.enums.exception.ExceptionEnums;
import com.chenyuxin.ilp.model.enums.exception.UserExceptionEnums;
import com.chenyuxin.ilp.model.pojo.Result;
import com.chenyuxin.ilp.service.user.CaptchaService;
import com.chenyuxin.ilp.service.user.VerificationCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    @Value("${verification.account}")
    private String account;
    @Value("${verification.key}")
    private String key;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private UserMapper userMapper;

    // 发送登录功能的短信验证码
    @Override
    public Result sendLoginVerificationCode(String phone,String captchaKey,String captcha) {
        if(!captchaService.verifyCaptcha(captchaKey,captcha)){
            throw new BaseException(UserExceptionEnums.CAPTCHA_ERROR);
        }
        // 检查验证码是否还未过期
        String code = stringRedisTemplate.opsForValue().get(RedisConstant.LOGIN_PHONE + phone);
        if(code!=null){
            throw new BaseException(UserExceptionEnums.PHONE_CODE_EXIST_ONE);
        }
        Boolean bool = this.sendSms(phone, RedisConstant.LOGIN_PHONE, 300,"【智能学习平台】您的注册验证码是:");
        if(!bool){
            throw new BaseException(ExceptionEnums.SYSTEM_ERROR);
        }
        return Result.ok(UserSuccessConstant.GET_VERIFICATION_CODE_SUCCESS,null);
    }
    // 发送注册功能的短信验证码
    @Override
    public Result sendRegisterVerificationCode(String phone,String captchaKey,String captcha) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User user = userMapper.selectOne(wrapper);
        if(user!=null){
            throw new BaseException(UserExceptionEnums.PHONE_REGISTERED);
        }
        if(!captchaService.verifyCaptcha(captchaKey,captcha)){
            throw new BaseException(UserExceptionEnums.CAPTCHA_ERROR);
        }
        // 检查验证码是否还未过期
        String code = stringRedisTemplate.opsForValue().get(RedisConstant.REGISTER_PHONE + phone);
        if (code!=null){
            throw new BaseException(UserExceptionEnums.PHONE_CODE_EXIST_THREE);
        }
        Boolean bool = this.sendSms(phone, RedisConstant.REGISTER_PHONE, 300,"【智能学习平台】您的注册验证码是:");
        if(!bool){
            throw new BaseException(ExceptionEnums.SYSTEM_ERROR);
        }
        return Result.ok(UserSuccessConstant.GET_VERIFICATION_CODE_SUCCESS,null);
    }
    @Override
    public Result verifyRegisterPhoneCode(String phone, String code){
        // 检查短信验证码是否正确
        // TODO
        if(code.equals("1234")){
            log.info("注册使用作弊验证码,phone:"+phone);
        }else{
            String correctCode = stringRedisTemplate.opsForValue().get(RedisConstant.REGISTER_PHONE + phone);
            if(StrUtil.isEmpty(correctCode)){
                throw new BaseException(UserExceptionEnums.REGISTER_TIMEOUT);
            }
            if(!code.equals(correctCode)){
                throw new BaseException(UserExceptionEnums.PHONE_CODE_ERROR);
            }
        }
        return Result.ok(UserSuccessConstant.VERIFY_CODE_SUCCESS,null);
    }

    /**
     * 发送短信验证码
     * @param phone 电话
     * @param preKey redis的key前缀
     * @param expireTime 过期时间(秒)
     * @return 成功：true
     */
    private Boolean sendSms(String phone,String preKey,Integer expireTime,String prefix){
        String redisKey = preKey+phone;
        // 随机生成验证码
        String content = RandomUtil.randomNumbers(4);
        String sendContent = prefix+content;
        // 将验证码保存到redis
        stringRedisTemplate.opsForValue().set(redisKey,content,expireTime,TimeUnit.SECONDS);
        // 调用发送短信api发送短信
        String url = "https://api.smsbao.com/sms";
        URI requestUri = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("u", account)
                .queryParam("p", key)
                .queryParam("m", phone)
                .queryParam("c", sendContent)
                .build()
                .encode()
                .toUri();
        // 发送请求
        RestTemplate restTemplate = new RestTemplate();
        String forObject = restTemplate.getForObject(requestUri, String.class);
        if(forObject.equals("0")){
            return true;
        }
        return false;
    }
}
